/**
 * author:Administrator
 * date:2016/3/19
 * desc:TODO
 */

"use strict";
let pubsubSystem = require('./pubsubSystem.js');
const EventEmitter = require('events').EventEmitter;
let co = require('co');

let uuid = require('uuid');
class Saga extends EventEmitter {
  constructor() {
    super();
    this.sagaId = uuid();
  }

  subscribe(eType) {
    pubsubSystem.subscribe(this.sagaId, eType, this._handler.bind(this));
  }

  _handler(event) {
    // console.log('Saga get event', event);
    let self = this;
    co(function*() {
      let type = event.type;
      let fnName = 'on' + type;
      let fn = self[fnName];
      if (fn) {
        yield fn.bind(self)(event);
      } else {
        console.error('no handler: ' + fnName);
      }
    }).catch(function (err) {
      console.error(err.stack);
    });
  }

  start() {
    throw new Error("should override this method");
  }

  _end(retObj) {
    this.fulfil && this.fulfil(retObj);
    let self = this;
    pubsubSystem.unSubscribe(self.sagaId);
  }

  /** 返回结果 */
  * result() {
    let self = this;
    let p = new Promise(function (fulfil, reject) {
      self.fulfil = fulfil;
    });
    return yield p;
  }
}
module.exports = Saga;